<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="app">
      <h2>动态组件</h2>
      <!-- <button @click="type = 1">btn1</button>
      <button @click="type = 2">btn2</button>
      <button @click="type = 3">btn3</button>
      <hr /> -->
      <!-- <child1 v-if="type === 1"></child1>
      <child2 v-if="type === 2"></child2>
      <child3 v-if="type === 3"></child3> -->

      <!--
        component组件用于做动态组件
        必须要配合is属性来做组件的切换

        动态组件在切换的过程中，组件默认会销毁和重新创建

        keep-alive表示缓存组件,可以让里面切换的组件不销毁和重新创建

        activated: 若组件实例是 <KeepAlive> 缓存树的一部分，当组件被插入到 DOM 中时调用。
        deactivated: 若组件实例是 <KeepAlive> 缓存树的一部分，当组件从 DOM 中被移除时调用。
      -->

      <button @click="comName = 'Child1'">btn1</button>
      <button @click="comName = 'Child2'">btn2</button>
      <button @click="comName = 'Child3'">btn3</button>
      <hr />

      <keep-alive>
        <component :is="comName"></component>
      </keep-alive>

      <hr />

      <!-- 子组件最外面的元素不要用li，option，tr -->
      <select>
        <!-- <option value="1">男</option>
        <option value="2">女</option> -->

        <option-child value="1" label="男"></option-child>
        <option-child value="2" label="女"></option-child>
      </select>
    </div>

    <script src="./lib/vue3.js"></script>
    <script>
      const { createApp } = Vue;

      const OptionChild = {
        props: ["value", "label"],
        template: `
          <option :value="value">{{ label }}</option>
        `,
      };

      const Child1 = {
        template: `
          <div>这是child1组件</div>
        `,
      };

      let timer;
      const Child2 = {
        data() {
          return {
            count: 1,
          };
        },
        template: `
          <div>这是child2组件 - {{ count }}</div>
        `,
        mounted() {
          console.log("child2组件被加载了");
          // setInterval(() => {
          //   this.count++;
          // }, 1000);
        },
        beforeUnmount() {
          console.log("child2组件被卸载了");
        },
        activated() {
          console.log("child2被插入了");
          timer = setInterval(() => {
            this.count++;
          }, 1000);
        },
        deactivated() {
          console.log("child2被移除了");
          clearInterval(timer);
        },
      };
      const Child3 = {
        template: `
          <div>这是child3组件</div>
        `,
      };

      const app = createApp({
        data() {
          return {
            type: 1,
            comName: "Child1",
          };
        },
        components: {
          Child1,
          Child2,
          Child3,
          OptionChild,
        },
      });

      app.mount("#app");
    </script>
  </body>
</html>
